package com.ruoyi.system.Fdongbei.service.impl.huayan.impl;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.system.Fdongbei.domain.*;
import com.ruoyi.system.Fdongbei.domain.dto.ZidonghuaYanDto;
import com.ruoyi.system.Fdongbei.domain.vo.TbZiDongHuayanVo;
import com.ruoyi.system.Fdongbei.service.*;
import com.ruoyi.system.Fdongbei.service.impl.huayan.IZidonghuayanService;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.time.LocalDateTime;
import java.util.Map;

@Service
public class zidonghuayanServiceImpl implements IZidonghuayanService {


    @Resource
    ITbGuozhongLiuchengService iTbGuozhongLiuchengService;
    @Resource
    IXzNameService iXzNameService;
    @Resource
    ITbGuozhongService iTbGuozhongService;

    @Resource
    ITbHetongHuayanService iTbHetongHuayanService;

    @Resource
    ITbHysfqfbzService iTbHysfqfbzService;


    @Resource
    ITbShJgService iTbShJgService;
    @Resource
    ITbHuayanService iTbHuayanService;

    @Resource
    ITbLogService iTbLogService;


    @Resource
    ITbZidonghuayanshibaijiluService iTbZidonghuayanshibaijiluService;

    @DataSource(value = DataSourceType.LY002_D)
    public String UploadDetectionResults(ZidonghuaYanDto zidonghuaYanDto) {
        TbZiDongHuayanVo tbHuayan = new TbZiDongHuayanVo();
        try {


            // 处理接收到的数据
            int testerID = zidonghuaYanDto.getTesterID();
            String cata = zidonghuaYanDto.getData().getDataInner().getCata();
            String samplingNo = zidonghuaYanDto.getData().getDataInner().getSamplingNo();
            List<ZidonghuaYanDto.Data.DataInner.TestResult> testResultList = zidonghuaYanDto.getData().getDataInner().getTestResultList();
            tbHuayan.setYmqybsm(samplingNo);//保存玉米纤样标识码
            Map<String, String> map = new HashMap<>();
            for (ZidonghuaYanDto.Data.DataInner.TestResult testResult : testResultList) {//保存初始数据
                switch (testResult.getTestName()) {
                    case "杂质":
                        map.put("杂质", testResult.getTestValue());
                        tbHuayan.setZz(Double.parseDouble(testResult.getTestValue()));
                        break;
                    case "不完善":
                        map.put("不完善", testResult.getTestValue());
                        tbHuayan.setBwsl(Double.parseDouble(testResult.getTestValue()));
                        break;
                    case "霉变":
                        map.put("霉变", testResult.getTestValue());
                        tbHuayan.setMbl(Double.parseDouble(testResult.getTestValue()));
                        break;
                    case "水分":
                        map.put("水分", testResult.getTestValue());
                        tbHuayan.setSf(Double.parseDouble(testResult.getTestValue()));
                        break;
                    case "容重":
                        map.put("容重", testResult.getTestValue());
                        tbHuayan.setRzsl(testResult.getTestValue());
                        break;
                    case "白玉米":
                        map.put("白玉米", testResult.getTestValue());
                        tbHuayan.setBnl(Double.parseDouble(testResult.getTestValue()));
                        break;

                }
            }
            String hth = iTbGuozhongLiuchengService.selecthth(samplingNo);//通过玉米纤样识别码查询过重流程获取合同号

            if ("".equals(hth)) {
                hth = "自然人";
            }


            tbHuayan.setZzh(
                    map.get("杂质")
            );
            String bz = "";
            String zzk = zzks_logic(tbHuayan.getZzh(), hth);
            String[] zzks = zzk.split(":");
            if (zzks[0].isEmpty()) {
                tbHuayan.setZzk(Double.parseDouble(zzks[1]));
            } else {
                bz += zzks[0];
            }
            tbHuayan.setBwslh(
                    map.get("不完善")
            );

            String bwsl = bwsls_logic(tbHuayan.getBwslh(), hth);
            String[] bwsls = bwsl.split(":");
            if (bwsls[0].isEmpty()) {
                tbHuayan.setBwslk(Double.parseDouble(bwsls[1]));
            } else {
                bz += bwsls[0];
            }
            tbHuayan.setMblh(
                    map.get("霉变")
            );
            String mbls = mbls_logic(tbHuayan.getMblh(), hth);
            String[] mblss = mbls.split(":");
            if (mblss[0].isEmpty()) {
                tbHuayan.setMblk(Double.parseDouble(mblss[1]));
            } else {
                bz += mblss[0];
            }

            String sf = sf_logic(tbHuayan.getSf().toString(), hth);
            String[] sfs = sf.split(":");
            if (sfs[0].isEmpty()) {
                tbHuayan.setSfk(Double.parseDouble(sfs[1]));
            } else {
                bz += sfs[0];
            }
            if (!"0.0".equals(tbHuayan.getBnl()) &&
                    tbHuayan.getBnl() != null
            ) {
                String bn = bnls_logic(tbHuayan.getBnl().toString(), hth);
                String[] bns = bn.split(":");
                if (bns[0].isEmpty()) {
                    tbHuayan.setBnlk(Double.parseDouble(bns[1]));
                } else {
                    bz += bns[0];
                }
            } else {
                tbHuayan.setBnlk(0.0);
            }

            tbHuayan.setBz(bz);
            tbHuayan.setRzdj(rz_logic(tbHuayan.getRzsl()));

            String gcl = "";
            String gcbz = iTbHysfqfbzService.selectByHth(hth);
            if (!gcbz.isEmpty()) {
                if (Double.parseDouble(tbHuayan.getSf().toString()) >= Double.parseDouble(gcbz)) {
                    gcl = "干粮";
                } else {
                    gcl = "潮粮";
                }
            }


            // 获取字符串值并转换为 BigDecimal，同时处理空指针和空字符串的情况
            BigDecimal zzzk = tbHuayan.getZzk() != null
                    ? new BigDecimal(tbHuayan.getZzk())
                    : BigDecimal.ZERO;

            BigDecimal sfk = tbHuayan.getSfk() != null
                    ? new BigDecimal(tbHuayan.getSfk())
                    : BigDecimal.ZERO;

            BigDecimal mblk = tbHuayan.getMblk() != null
                    ? new BigDecimal(tbHuayan.getMblk())
                    : BigDecimal.ZERO;

            BigDecimal bmk = tbHuayan.getBnlk() != null
                    ? new BigDecimal(tbHuayan.getBnlk())
                    : BigDecimal.ZERO;

// 计算总和
            BigDecimal total = zzzk.add(sfk).add(mblk).add(bmk);
            Double.parseDouble(tbHuayan.getBnlk().toString());
            tbHuayan.setZk(Double.parseDouble(String.valueOf(total)));
            TbGuozhong tbGuozhong = iTbGuozhongService.selectByYmqybsm(tbHuayan.getYmqybsm());
            tbHuayan.setCzbh(tbGuozhong.getCzbh());
            String jg = upload_huayan(tbHuayan.getYmqybsm(), gcl, tbHuayan.getRzdj(), tbGuozhong);

            tbHuayan.setCysj(LocalDateTime.now());
            tbHuayan.setHycs(3);
            tbHuayan.setHybs(2);

            iTbHuayanService.updatehuayan(tbHuayan);

// 将 double 转换为 BigDecimal，避免精度丢失
            BigDecimal zkValue = new BigDecimal(Double.toString(tbHuayan.getZk()));

// 创建一个值为 100 的 BigDecimal
            BigDecimal hundred = new BigDecimal("100");

// 进行除法操作，并保留两位小数，使用四舍五入
            BigDecimal result = zkValue.divide(hundred, 2, RoundingMode.HALF_UP);

// 调用更新方法，并将结果转换为字符串
            iTbGuozhongService.updatehykz(result.toString(), tbHuayan.getYmqybsm());
            //  iTbGuozhongService.updatehykz(String.valueOf(Double.parseDouble(tbHuayan.getZk()) / 100), tbHuayan.getYmqybsm());
            if ("SH".equals(tbGuozhong.getGblx())) {
                iTbGuozhongService.updatejsdj(jg, gcl, tbHuayan.getYmqybsm());
            }
            return "0";
        } catch (Exception e) {
            iTbZidonghuayanshibaijiluService.insertzidonghuayan(new TbZidonghuayanshibaijilu(
                    tbHuayan.getZz().toString(),
                    tbHuayan.getMbl().toString(),
                    tbHuayan.getBnl().toString(),
                    tbHuayan.getBwsl().toString(),
                    tbHuayan.getSf().toString(),
                    tbHuayan.getRzsl().toString(),
                    tbHuayan.getBz(),
                    "-1",
                    tbHuayan.getYmqybsm(),
                    LocalDateTime.now().toString())
            );


            return "-1";
        }
    }


    private String streamGetValue(List<ZidonghuaYanDto.Data.DataInner.TestResult> testResultList, String name) {
        return testResultList
                .stream()
                .filter(map -> name.equals(map.getTestName())) // 过滤出testName为"水分"的对象
                .map(map -> map.getTestValue()) // 提取testValue为double
                .findFirst() // 获取第一个匹配的值
                .orElse("未找到"); // 如果没有找到，返回默认值
    }

    //单价
    public String upload_huayan(String ymqybsm, String gcl, String rzdj, TbGuozhong tbGuozhong) {

        if (!"SH".equals(tbGuozhong.getGblx())) {
            return "";
        }
        String fdjg = "";
        if (" ".equals(tbGuozhong.getJshth()) || tbGuozhong.getJshth() == null || "".equals(tbGuozhong.getJshth())) {
            fdjg = iTbHetongHuayanService.selectByHth("自然人");
        } else {
            fdjg = iTbHetongHuayanService.selectByHth(tbGuozhong.getJshth());
        }
        if (fdjg != null) {
            if (fdjg.isEmpty()) {
                fdjg = "10";
            }
        } else {
            fdjg = "10";
        }

        String jg = "";
        if ("干粮".equals(gcl)) {
            jg = iTbShJgService.selectSHjgByczbh_jg(tbGuozhong.getCzbh());
        } else if ("潮粮".equals(gcl)) {
            jg = iTbShJgService.selectSHjgByczbh_jg2(tbGuozhong.getCzbh());

        }
        switch (rzdj) {
            case "一二等":
                jg = new BigDecimal(jg).add(new BigDecimal(fdjg).divide(new BigDecimal("1000"))).toString();
                break;
            case "三等":
                break;
            case "四等":
                jg = new BigDecimal(jg).subtract(new BigDecimal(fdjg).divide(new BigDecimal("1000"))).toString();
                break;
            case "等外":
                jg = new BigDecimal(jg).subtract(new BigDecimal(fdjg).divide(new BigDecimal("1000"))
                        .multiply(new BigDecimal("2"))).toString();
                break;
        }

        return jg;

    }


    // 容重
    public String rz_logic(String rz) {
        int rrzzhh = Integer.parseInt(rz);
        String rzdj = "";
        if (rrzzhh >= 690) {
            rzdj = "一二等";
        } else if (rrzzhh >= 660) {
            rzdj = "三等";
        } else if (rrzzhh >= 570) {
            rzdj = "四等";
        } else {
            rzdj = "等外";
        }
        return rzdj;
    }

    // 杂质
    public String zzks_logic(String zz, String hth) {
        return calculateResult(zz, hth, iXzNameService.selectxzname(zz, hth), "杂质超标拒收");
    }

    // 不完善
    public String bwsls_logic(String bws, String hth) {
        return calculateResult(bws, hth, iXzNameService.selectxznameBwsls(bws, hth), "不完善超标拒收");
    }


    // 霉变
    public String mbls_logic(String mb, String hth) {
        return calculateResult(mb, hth, iXzNameService.selectxznameMbl(mb, hth), "霉变超标拒收");
    }

    //水分u
    private String sf_logic(String sf, String hth) {
        return calculateResult(sf, hth, iXzNameService.selectxznamesf(sf, hth), "水分超标拒收");
    }

    //白懦
    private String bnls_logic(String bn, String hth) {
        return calculateResult(bn, hth, iXzNameService.selectxznameBn(bn, hth), "白懦超标拒收");
    }

    //判断逻辑
    private String calculateResult(String value, String hth, XzName xzName, String rejMsg) {
        if (hth != null && hth.isEmpty()) {
            return ",未查询到合同号:";
        }

        if (xzName == null) {
            return ",未查询到标准" + rejMsg + ":";
        }

        String result = "";
        String bz = ""; // 备注

        if ("拒收".equals(xzName.getZt())) {
            bz = "," + rejMsg;
        }
        if ("不扣".equals(xzName.getZt())) {
            result = "0";
        } else {
            result = calculateFinalResult(value, xzName);
        }


        return bz + ":" + result;
    }


    //计算逻辑
    private String calculateFinalResult(String value, XzName xzName) {
        try {
            Double B = xzName.getJb();
            Double F = xzName.getKb();
            Double D = xzName.getJk();
            Double A001 = Double.parseDouble(value) - B;
            Double B002 = F * A001;
            String W11 = String.format("%.1f", B002);
            Double W12 = Double.parseDouble(W11);
            Double C001 = W12 + D;
            return String.format("%.1f", C001);
        } catch (NumberFormatException e) {
            return "解析失败";
        }
    }

}